package com.fone.player.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.fone.player.R;
import com.fone.player.entity.DownloadItem;
import com.fone.player.util.FileUtils;
import com.fone.player.util.L;
import com.fone.player.util.SystemUtil;

/**
 * 下载handler
 * 
 * @author JasonZue
 * @since 2014-5-19
 */

public class DownloadHandler {
	private static final String TAG = DownloadHandler.class.getSimpleName();

	public static final int DOWNLOAD_UPDATE = 1; // 更新下载进度
	public static final int DOWNLOAD_COMPLETE = 2; // 下载完成
	public static final int DOWNLOAD_FAIL = 4; // 下载失败
	public static final int REQEUSTFAIL = 7;// 请求失败
	public static final int SDCARD_NOSPACE = 8;// SD卡空间不足

	// TODO 需要修改默认路径
	private final String APK_PATH = Environment.getExternalStorageDirectory()
			+ "/";

	private Context mContext;
	private NotificationManager mNotificationManager;

	private RemoteViews mRemoveViews;

	private HashMap<String, Notification> notificationMap = new HashMap<String, Notification>();
	private ArrayList<String> urlList = new ArrayList<String>();

	public DownloadHandler(Context mContext) {
		this.mContext = mContext;
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {

		@Override
		public synchronized void handleMessage(Message msg) {
			super.handleMessage(msg);
			DownloadItem downitem = (DownloadItem) msg.obj;
			if (msg != null) {
				switch (msg.what) {
				case DOWNLOAD_UPDATE:
					// 下载(更新通知信息)
					if (mNotificationManager == null) {
						mNotificationManager = (NotificationManager) mContext
								.getSystemService(Context.NOTIFICATION_SERVICE);
					}
					Notification notifcation = getNotifcation(downitem.url);
					notifcation.tickerText = downitem.itemName + "";
					mRemoveViews = new RemoteViews(mContext.getPackageName(),
							R.layout.update);
					mRemoveViews.setTextViewText(R.id.down_title,
							downitem.itemName);
					mRemoveViews.setTextViewText(R.id.tvProcess, "已下载"
							+ downitem.itemPercent + "%");
					mRemoveViews.setProgressBar(R.id.pbDownload, 100,
							downitem.itemPercent, false);
					notifcation.contentView = mRemoveViews;
					mNotificationManager.notify(downitem.url.hashCode(),
							notifcation);

					break;
				case DOWNLOAD_COMPLETE:
					if (mNotificationManager != null
							&& notificationMap.get(downitem.url) != null) {
						mNotificationManager.cancel(downitem.url.hashCode());
						notificationMap.remove(downitem.url);
					}
					File newFile = new File(downitem.localFilePath);
					install(newFile, mContext);
					break;
				case DOWNLOAD_FAIL:
					if (mNotificationManager != null
							&& notificationMap.get(downitem.url) != null) {
						mNotificationManager.cancel(downitem.url.hashCode());
						notificationMap.remove(downitem.url);
					}
					// if(customDialog!=null)
					// customDialog.dismiss();
					// CommonUtil.showToast(R.string.downloadfail, 0);
					break;
				case REQEUSTFAIL:
					Toast.makeText(mContext, "网络出错", Toast.LENGTH_SHORT).show();

					break;
				// case ViewControl.NETWORKERROR_NUM:
				// if (mNotificationManager != null &&
				// notificationMap.get(downitem.url)!=null)
				// {
				// mNotificationManager.cancel(downitem.url.hashCode());
				// notificationMap.remove(downitem.url);
				// }
				// break;
				case SDCARD_NOSPACE:

					if (mNotificationManager != null
							&& notificationMap.get(downitem.url) != null) {
						mNotificationManager.cancel(downitem.url.hashCode());
						notificationMap.remove(downitem.url);
					}
					// if (customDialog != null){
					// customDialog.dismiss();
					// }
					Toast.makeText(mContext, "SD卡容量不足", Toast.LENGTH_SHORT)
							.show();
					break;
				default:
					break;
				}
			}
		}

	};

	private Notification getNotifcation(String url) {
		Notification notification = null;
		if (notificationMap.get(url) == null) {
			notification = new Notification();
			notification.icon = android.R.drawable.stat_sys_download;
			notification.when = System.currentTimeMillis();
			notification.defaults = Notification.DEFAULT_LIGHTS;
			Intent intent = new Intent(mContext.getApplicationContext(),
					mContext.getClass());
			PendingIntent contentIntent = PendingIntent.getActivity(mContext,
					0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
			notification.contentIntent = contentIntent;
			notificationMap.put(url, notification);
		} else {
			notification = notificationMap.get(url);
		}

		return notification;
	}

	/**
	 * 安装下载后的apk文件
	 * 
	 * @param file
	 * @param context
	 * @return void
	 * @throws
	 */
	private void install(File file, Context context) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		context.startActivity(intent);

	}

	/**
	 * 下载APK
	 * 
	 * @param url
	 * @param showInfo
	 * @return void
	 * @throws
	 */
	public void downApk(String url, String showInfo) {
		L.v(TAG, "start apk Load", url);

		if (FileUtils.getFreeDiskSpace() == -1) {
			mHandler.post(new Runnable() {

				@Override
				public void run() {
					// 提示内存不足
					Toast.makeText(mContext, "您的存储空间不足,请清理后重试",
							Toast.LENGTH_SHORT).show();
				}
			});
			return;
		}
		L.i("tesetDOn", urlList.toString() + "    " + url);
		if (!urlList.contains(url)) {
			urlList.add(url);
			DownloadItem downloadItem = DownloadItem.getInstence();
			Message message = new Message();
			message.what = DOWNLOAD_UPDATE;
			downloadItem.url = url;
			downloadItem.itemName = showInfo;
			downloadItem.itemPercent = 0;
			message.obj = downloadItem;
			mHandler.sendMessage(message);
			HttpClient client = new DefaultHttpClient();
			// 请求超时
			client.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
			// 读取超时
			client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
					60000);
			InputStream instream = null;
			try {
				HttpGet get = new HttpGet(url);

				HttpResponse response = client.execute(get);

				if (response.getStatusLine().getStatusCode() == 200) {
					HttpEntity entity = response.getEntity();
					long lenth = entity.getContentLength();

					instream = entity.getContent();

					if (SystemUtil.sdCardIsAvailable()) {
						File dirFile = new File(APK_PATH);

						if (!dirFile.exists()) {
							dirFile.mkdirs();
						}
						File myCaptureFile = new File(APK_PATH + url.hashCode()
								+ ".fonedw");

						if (!myCaptureFile.exists()) {
							myCaptureFile.createNewFile();
						}
						// 得到文件的二进制数据，以二进制封装得到数据，具有通用性
						if (FileUtils.getFreeDiskSpace() * 1024 > lenth) {
							try {
								//
								readInputStream(instream, lenth, showInfo, url,
										myCaptureFile);
								client.getConnectionManager().shutdown();
							} catch (Exception e) {
								//
								message = new Message();
								message.what = DOWNLOAD_FAIL;
								message.obj = downloadItem;
								downloadItem.url = url;
								mHandler.sendMessage(message);
								urlList.remove(url);
								if (instream != null)
									instream.close();
								client.getConnectionManager().shutdown();
								return;
							}
						} else {
							//
							message = new Message();
							message.what = SDCARD_NOSPACE;
							message.obj = downloadItem;
							downloadItem.url = url;
							mHandler.sendMessage(message);
							urlList.remove(url);
							if (instream != null)
								instream.close();
							client.getConnectionManager().shutdown();
							return;
						}

						String filename = url.substring(url.lastIndexOf("/"));

						File newFile = new File(myCaptureFile.getParent()
								+ filename);

						newFile.createNewFile();
						L.i("changName", newFile.getName());
						myCaptureFile.renameTo(newFile);

						downloadItem.itemName = showInfo;
						downloadItem.itemPercent = 0;
						downloadItem.url = url;
						downloadItem.localFilePath = newFile.getAbsolutePath();
						message = new Message();
						message.what = DOWNLOAD_COMPLETE;
						message.obj = downloadItem;
						// message =
						// mHandler.obtainMessage(DOWNLOAD_COMPLETE,downloadItem);
						mHandler.sendMessage(message);
						urlList.remove(url);

					} else {

						message = new Message();
						message.what = SDCARD_NOSPACE;
						message.obj = downloadItem;
						downloadItem.url = url;

						mHandler.sendMessage(message);
						urlList.remove(url);
						if (instream != null)
							try {
								instream.close();
							} catch (IOException e1) {
								e1.printStackTrace();
							}
						client.getConnectionManager().shutdown();
					}

				}

			} catch (Exception e) {
				e.printStackTrace();
				message = new Message();
				message.what = DOWNLOAD_FAIL;
				message.obj = downloadItem;
				downloadItem.url = url;
				mHandler.sendMessage(message);
				urlList.remove(url);
				if (instream != null)
					try {
						instream.close();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				client.getConnectionManager().shutdown();
			}
		}

	}

	public void readInputStream(InputStream inStream, long lenth, String title,
			String url, File file) throws Exception {
		FileOutputStream outStream = new FileOutputStream(file);
		byte[] buffer = new byte[1024];
		int mDownloadPrecent = 0;
		int read;
		long count = 0;
		int precent = 0;
		DownloadItem downitem = DownloadItem.getInstence();
		while ((read = inStream.read(buffer)) != -1) {

			outStream.write(buffer, 0, read);
			count += read;
			precent = (int) (((double) count / lenth) * 100);
			// 每下载完成5%就通知任务栏进行修改下载进度
			if (precent - mDownloadPrecent >= 5) {
				mDownloadPrecent = precent;
				downitem.itemPercent = precent;
				downitem.itemName = title;
				downitem.url = url;
				Message message = new Message();
				message.what = DOWNLOAD_UPDATE;
				message.obj = downitem;
				L.i("loadpercentloadpercent:", precent + "");
				mHandler.sendMessage(message);
			}
		}
		outStream.close();
		inStream.close();

	}

}
